<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogTableVisible" width="70%" :close-on-click-modal="false"
    :before-close="handleClose">
    <el-button style="float: left;margin-right: 20px;" type="primary" @click="logload" plain icon="el-icon-download"
      size="medium">
      下载备件耗材基值导入模板</el-button>
    <el-upload :action="uploadFileUrl" :multiple="false" :show-file-list="false" :headers="headers"
      accept=".xlsx,csv,application/vnd.ms-excel,applications/vnd.openxmlforms-officedocument.spreadsheetml.sheet"
      :http-request="httpRequest">
      <el-button type="primary" plain icon="el-icon-upload2" size="medium">上传文件</el-button>
    </el-upload>
    <h4>解析结果：</h4>
    <div class="file_div">
      <el-scrollbar style="width:100%;">
        <el-table :data="tableData" :loading="loading">
          <el-table-column prop="物料名称" label="物料名称" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="类别名称" label="类别名称" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column prop="规格型号" label="规格型号" min-width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="单位名称" label="单位名称" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column prop="类型（耗材,备件）" label="类型（耗材,备件）" min-width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="供应商名称" label="供应商名称" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column prop="库存预警下限" label="库存预警下限" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="库存预警上限" label="库存预警上限" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="采购周期（天）" label="采购周期（天）" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="更换周期（天）" label="更换周期（天）" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="备注" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
        </el-table>
      </el-scrollbar>
    </div>
    <div align="center" slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="btnloading" @click="submitForm">导入</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { importConsumableBaseTemplate, importConsumableBaseExcel } from '@/api/deviceConsumable/management'
import { getToken } from "@/utils/auth";
const XLSX = require('xlsx');
export default {
  name: 'Form',
  data () {
    return {
      dialogTableVisible: false,
      tableData: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      loading: false,
      btnloading: false,
      dialogTitle: '导入基值列表'
    }
  },
  methods: {
    // 打开表单对话框
    openDialog () {
      this.dialogTitle = '导入基值列表';
      this.dialogTableVisible = true;
    },
    /**
     * 创建下载链接
     */
    logload () {
      let data = {};
      let filename = '备件耗材基值列表模板.xlsx';
      importConsumableBaseTemplate(data, filename).then()
      // // dom中创建a标签
      // let aTag = document.createElement('a')
      // // 给创建的a标签添加href属性并赋值
      // aTag.href = `http://139.159.212.47:9310/statics/2022/08/29/1f08efe5-2f09-4902-9ecd-f8a31989a38e.xlsx`
      // aTag.download = '备件耗材基值列表.xlsx'
      // // 自动点击创建的标签
      // aTag.click()
    },
    submitForm () {
      if (this.tableData.length === 0) return this.$message.error('请选择导入文件')
      this.btnloading = true
      let formData = new FormData();
      formData.append('file', this.fileList)
      importConsumableBaseExcel(formData).then((res) => {
        this.$message.success('操作成功')
        this.btnloading = false
        this.dialogTableVisible = false
        this.$emit('submit_success')
      }).catch(() => {
        this.btnloading = false
      })
    },
    /** 导入解析json格式 */
    httpRequest (e) {
      let file = e.file
      console.log('e', e);
      this.fileList = e.file
      this.loading = true
      if (!file) {
        //没有文件
        this.loading = false
        return false
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        //格式根据自己需求定义
        this.loading = false
        return this.$message.error('格式上传不正确,请上传xls,xlsx格式文件！')
      }
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          // console.log(XLSX);
          const data = ev.target.result
          const workbook = XLSX.read(data, { type: 'binary' })//字符编码解析
          const exlname = workbook.SheetNames[0]//取第一张表
          const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname])//生成json表格内容
          console.log(exl);
          this.tableData = exl
          this.loading = false
          document.getElementsByName('file')[0].value = ''
        } catch (error) {
          console.log('出错了', error);
          this.loading = false
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },
    // 取消事件------------
    handleClose () {
      this.dialogTableVisible = false;
      this.tableData = [];
    }
  }
}
</script>
<style lang="scss" scoped>
.file_div {
  padding: 5px;
  border: 1px solid #999;
  border-radius: 10px;
}
</style>
